const Service = require("egg").Service;
const axios = require("axios");

class WeixindbService extends Service {
  // 获取群聊列表，并更新数据库中的数据
  async updateWxList() {
    const { ctx } = this;
    await ctx.model.Weixindb.deleteMany({});

    try {
      const response = await axios.post(this.config.baseURL, {
        type: "getWeChatList",
        data: {},
      });

      // 检查响应状态
      const datalist = response.data.result;
      // 清空Weixindb表中的数据，然后重新插入新的数据
      await Promise.all(
        datalist.map((obj) =>
          ctx.model.Weixindb.create({
            startTimeStamp: obj.startTimeStamp,
            startTime: obj.startTime,
            runTime: obj.runTime,
            recv: obj.recv,
            send: obj.send,
            wxNum: obj.send,
            nick: obj.nick,
            wxid: obj.wxid,
            expireTime: obj.expireTime,
            isExpire: obj.isExpire,
            phone: obj.phone,
            avatarUrl: obj.avatarUrl,
            country: obj.country,
            province: obj.province,
            city: obj.city,
            email: obj.email,
            qq: obj.qq,
            sign: obj.sign,
            pid: obj.pid,
            port: obj.port,
            timestamps: response.data.timestamps,
          })
        )
      );
      return response.data;
    } catch (error) {
      // 捕获异常并返回错误信息
      this.logger.error("获取失败:", error.message);
      return {
        success: false,
        message: "请求失败，请检查网络或接口状态",
      };
    }
  }

  async getWxInfo(wxid) {
    const { ctx } = this;
    try {
      const weixin = await ctx.model.Weixindb.findOne({ wxid });
      return weixin;
    } catch (error) {
      ctx.logger.error("查询微信群记录失败:", error);
      throw new Error("查询群记录时发生异常");
    }
  }

  async getWxList() {
    const { ctx } = this;
    try {
      const data = await ctx.model.Weixindb.find();
      return data;
    } catch (error) {
      // 捕获异常并返回错误信息
      this.logger.error("获取用户信息失败:", error.message);
      return {
        success: false,
        message: "请求失败，请检查网络或接口状态",
      };
    }
  }

  // 修改数据
  async editWeixin(mywxid, field) {
    const { ctx } = this;
    try {
      const result = await ctx.model.Weixindb.findOneAndUpdate(
        { wxid: mywxid },
        { $set: field },
        { new: true }
      );

      if (!result) {
        throw new Error("未找到该微信");
      }

      return result;
    } catch (error) {
      this.logger.error("更新微信状态失败:", error);
      throw error;
    }
  }

  // 微信状态检测
  async checkWeChat(mywxid) {
    const { ctx } = this;
    try {
      const response = await axios.post(
        this.config.baseURL,
        {
          type: "checkWeChat",
          data: {},
        },
        {
          params: { wxid: mywxid },
        }
      );
      // 检查响应状态
      return response;
    } catch (error) {
      // 捕获异常并返回错误信息
    }
  }
}

module.exports = WeixindbService;
